package org.bonorsoft.modules.system.shiro.authc.aop;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.util.DeviceUtil;
import org.bonorsoft.common.util.ServletUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.system.shiro.authc.JwtToken;
import org.bonorsoft.modules.system.shiro.vo.DefContants;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * @Description: 鉴权登录拦截器
 * @Author: WilliamYe
 * @Date: 2018/10/7
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            executeLogin(request, response);
            return true;
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage());
        }
    }

    /**
     *
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws AuthenticationException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //在request headers中添加X-Access-Token请求参数
        //String token = httpServletRequest.getHeader(DefContants.X_ACCESS_TOKEN);

        String parameter_token = httpServletRequest.getParameter(DefContants.TOKEN);
        String header_token = httpServletRequest.getHeader(DefContants.X_ACCESS_TOKEN);
        String token = oConvertUtils.isNotEmpty(parameter_token) ? parameter_token : header_token;

        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        // 如果没有抛出异常则代表登入成功，返回true
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        try {
            super.preHandle(request, response);
        } catch (Exception e) {
            //super.redirectToLogin(request, response);
            responseError(request, response, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 将非法请求跳转到 /filterError/**中
     */
    private void responseError(ServletRequest request, ServletResponse response, int code, String message) {
        System.out.println(message);
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            //设置编码，否则中文字符在重定向时会变为空字符串
            message = URLEncoder.encode(message, "UTF-8");
            String uri = httpServletRequest.getRequestURI();
            //判断是否来自移动端
            if (uri.contains("wechat")) {
                httpServletResponse.sendRedirect("/wechatError/" + code + "/" + message);
            } else if (uri.contains("qrcode/detail")) {
                String[] split = uri.split("/");
                httpServletResponse.sendRedirect("/detailError/" + split[split.length - 1]);

            }else if (ServletUtils.isAjaxRequest((HttpServletRequest) request)) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.error(message)));
            } else {//PC端
                //如果有项目名称路径记得加上
                httpServletResponse.sendRedirect("/filterError/" + code + "/" + message);
//                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
